package org.shagin.jfin.date.cond;

import static java.util.Calendar.FRIDAY;
import static java.util.Calendar.MONDAY;
import static java.util.Calendar.SATURDAY;
import static java.util.Calendar.SUNDAY;
import static java.util.Calendar.THURSDAY;
import static java.util.Calendar.TUESDAY;
import static java.util.Calendar.WEDNESDAY;
import static org.shagin.jfin.date.DateUtils.getWeekDay;

import java.util.Calendar;
import java.util.Date;

/**
 * The Class Weekly.
 */
@SuppressWarnings("serial")
public class Weekly extends DateCondition {

    public static int[] WORKING_DAYS = new int[]{MONDAY, TUESDAY, WEDNESDAY,
            THURSDAY, FRIDAY};

    public static int[] WEEK_END = new int[]{SATURDAY, SUNDAY};

    private int[] weekdays = new int[0];

    /**
     * Instantiates a new weekly.
     * 
     * @param weekdays the weekdays
     */
    public Weekly(int[] weekdays) {
        this.weekdays = weekdays;
    }

    /**
     * Instantiates a new weekly.
     * 
     * @param dayOfWeek the day of week
     */
    public Weekly(int dayOfWeek) {
        this(new int[]{dayOfWeek});
    }

    /**
     * {@inheritDoc}
     */
    public boolean validDate(Date date) {
        if (!super.validDate(date))
            return false;

        boolean result = false;
        if (weekdays.length > 0) {
            cal.setTime(date);
            int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
            for (int i = 0; i < weekdays.length; i++) {
                if (weekdays[i] == dayOfWeek) {
                    result = true;
                    break;
                }
            }
        }

        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return "Еженедельно " + toWeekDays(weekdays) + " " + toString(range);
    }

    /**
     * To week days string.
     * 
     * @param array the array
     * @return the string
     */
    public static String toWeekDays(int[] array) {
        String result = "";
        for (int i = 0; i < array.length; i++) {
            result += getWeekDay(array[i]) + (i < array.length - 1 ? "," : "");
        }
        return result;
    }

    /**
     * Gets the week days.
     * 
     * @return the week days
     */
    public int[] getWeekDays() {
        return weekdays;
    }

    /**
     * Sets the week days.
     * 
     * @param weekdays the new week days
     */
    public void setWeekDays(int[] weekdays) {
        this.weekdays = weekdays;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String format() {
        return "Weekly(" + join(weekdays) + ")";
    }
}
